<?php
$config["startup"][]="TriggersRegenerate";
$config["timer"][]="TriggersTimer";



function TriggersTimer(){
	global $config;	
	if (time()>$config["TVUpcomingTimer"]){
		//send xAP Messages
		TimersCheck();
		xAPLog("TV","Upcoming TV","");
		// set next check for 1 minutes
		$config["TVUpcomingTimer"]=time()+(60);
	}
	
}
function TimersCheck(){
	// look at database and find anything that needs triggering
	global $config;	
	$now=date("Y-m-d H:i:s");
	$sql="select * from xap_tv_prog where triggertime< '".$now."' and triggerevent<>''";
	$results=dbquery($sql);
	foreach($results as $row){
		EventRunBySource("TV","Upcoming Program Alert",$row,"To remind of upcoming programs");
		dbexec("update xAP_TV_prog set TriggerEvent='' where ProgID=".$row["ProgID"]); // Done so remove setting
	}
	
	
}
function TriggersRegenerate(){
global $config;	
	// go through all programms and mark for events
	$results=dbquery("select * from xAP_TV_Trigger");
	$now=date("Y-m-d H:i:s");
	
	dbexec("update xAP_TV_Prog set TriggerTime='',TriggerEvent=''");

	foreach($results as $row){

	$prog=str_replace("*","%",$row["ProgName"]);
	$desc=str_replace("*","%",$row["ProgDesc"]);
	$channel=$row["ChannelName"];
	if ($prog!="" || $desc!=""){
	
		if ($config["database"]=="sqlite" || $config["database"]=="sqlite3"){
			$sql="update xAP_TV_Prog set 
			TriggerTime=datetime(ProgStart,'-".$row["Delay"]." minutes'),
			TriggerEvent='TV'
			where
			ProgStart>='".$now."' and 
			";
		}else{
			$sql="update xAP_TV_Prog set 
			TriggerTime=ADDDATE(ProgStart, INTERVAL -".$row["Delay"]." MINUTE),
			TriggerEvent='TV'
			where
			ProgStart>='".$now."' and 
			";
		}
		
		
		if($prog!=""){$sql.=" ProgName like '".dbesc($prog)."' and ";}
		if($desc!=""){$sql.=" ProgDesc like '".dbesc($desc)."' and ";}
		if($channel!=""){$sql.=" ChannelName='".dbesc($channel)."' and ";}
		$sql=substr($sql,0,strlen($sql)-4);
		dbexec($sql);
	}

	}

}
?>